import React, { useEffect, useState, useCallback } from 'react';
import Button from 'antd/es/button';
import { useHistory, useLocation } from 'react-router-dom';
import { LeftOutlined } from '@ant-design/icons';
import { Row, Col, Space, Form, Input, Select, Switch, message } from 'antd';

import { useForm } from 'antd/lib/form/Form';
import { Store } from 'antd/lib/form/interface';
import { addQa, modifyQa, getQa, getFlowNodes } from 'admin/servers/servers';

import { FlowNodesResponse } from 'admin/schema/QuestionAnswer';
import qs from 'query-string';
import ExtendQuestion from '../extendQuestion';
const layout = {
  labelCol: { span: 4 },
};
const Option = Select.Option;
/**电信特殊需求-表格-展示扩展问题列表 */
const OperateQa: React.FC = () => {
  // 问答表单
  const [form] = useForm();
  // 当前回答流程的选项
  const [answerFlowType, setAnswerFlowType] = useState<number | null>(null);
  // 路由location
  const location = useLocation();
  const history = useHistory();
  // URL查询字符串=>对象
  const query = qs.parse(location.search);
  // 问答ID
  const [questionId, setQuestionId] = useState<number>(
    query.questionId ? Number(query.questionId) : 0
  );

  // 保存按钮loading
  const [saveLoading, setSaveLoading] = useState<boolean>(false);

  // 保存按钮-是否可用
  const [saveDisable, setSaveDisable] = useState(false);

  // 选择节点列表
  const [flowNodes, setFlowNodes] = useState<FlowNodesResponse[]>();

  /**
   * 获取跳转节点列表
   */
  const getFlowNodeList = useCallback(async () => {
    try {
      const res = await getFlowNodes({ versionId: Number(query.versionId) });
      if (res.code === 0) {
        setFlowNodes(res.data || []);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [query.versionId]);
  /**
   * 获取当前回答流程状态
   */
  const getAnswerFlowType = useCallback(() => {
    const type = form.getFieldValue('answerFlowType');
    if (type === 3) {
      getFlowNodeList();
    }
    setAnswerFlowType(type);
  }, [form, getFlowNodeList]);

  /**
   * 提交表单
   */
  const onFinish = async (values: Store) => {
    setSaveLoading(true);
    console.log('onFinish -> values', values);
    const { interruptSwitch, answer, answerFlow, answerFlowType, questionDescribe } = values;
    try {
      // 当前为创建模式 && 第一次创建
      if (!questionId) {
        // 创建问答库
        const res = await addQa({
          versionId: Number(query.versionId),
          interruptSwitch: interruptSwitch ? 'on' : 'off',
          answer: answer.trim(),
          answerFlow,
          answerFlowType,
          questionDescribe: questionDescribe.trim(),
        });
        if (res.code === 0) {
          message.success('新增问答成功');
          const newId = res.data.questionId;
          setQuestionId(newId);
          // 替换路由
          history.replace(
            `/webapp/outbound/ai/robots/version/flow/operateQa?versionId=${query.versionId}&questionId=${newId}`
          );
        } else {
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      } else {
        // 编辑问答库
        const res = await modifyQa({
          questionId: questionId, // 二次保存 || 编辑
          interruptSwitch: interruptSwitch ? 'on' : 'off',
          answer: answer.trim(),
          answerFlow,
          answerFlowType,
          questionDescribe: questionDescribe.trim(),
        });
        if (res.code === 0) {
          message.success('编辑问答成功');
        } else {
          message.error(`${res.tips}(错误码: ${res.code})`);
        }
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setSaveLoading(false);
  };

  // 数据初始化 && 数据更新
  // 1. 进入页面, 判断是创建还是编辑
  // 2. 创建则无处理, 等待用户操作
  // 3. 创建问答完成后, 更新questionId, 方便二次保存
  // 4. 编辑则根据questionId加载当前编辑问答的信息
  // 5. 点击保存更新指定questionId表单信息
  // 6. table: 新建扩展, 判断当前questionId, 有则允许创建, 无则提示先创建问答

  const initQa = useCallback(async () => {
    try {
      let initForm = {
        answer: '',
        interruptSwitch: false,
        answerFlow: 0,
        answerFlowType: 0,
        questionDescribe: '',
      };
      // 如果是有questionId: 说明是编辑或二次创建保存
      if (questionId) {
        // 查询当前问答信息
        const res = await getQa({
          questionId: questionId,
        });
        const { answer, interruptSwitch, answerFlow, answerFlowType, questionDescribe } = res.data;
        initForm = {
          answer,
          interruptSwitch: interruptSwitch === 'on',
          answerFlow,
          answerFlowType,
          questionDescribe,
        };
      }
      // 初始化问答form
      form.setFieldsValue(initForm);
      getAnswerFlowType();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [form, getAnswerFlowType, questionId]);

  useEffect(() => {
    initQa();
  }, [initQa]);

  // 保存按钮：启用、禁用
  function updateSave(val: boolean) {
    setSaveDisable(val);
  }
  return (
    <>
      <div className="nav">
        <Button
          type="link"
          onClick={() => {
            history.goBack();
          }}
        >
          <LeftOutlined />
          返回
        </Button>
        <div className="title">{questionId ? '编辑问答' : '新建问答'}</div>
      </div>
      <div className="operateQa-head">
        <Form form={form} {...layout} onFinish={onFinish}>
          <Row gutter={[0, 10]}>
            <Col span={12}>
              <Form.Item
                label="问题描述"
                name="questionDescribe"
                rules={[{ required: true, max: 50, whitespace: true }]}
              >
                <Input.TextArea
                  placeholder="请输入问题，50个以内字符"
                  maxLength={50}
                ></Input.TextArea>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="答案设置"
                name="answer"
                rules={[{ required: true, max: 350, whitespace: true }]}
              >
                <Input.TextArea
                  placeholder="请输入答案，350个以内字符"
                  maxLength={350}
                ></Input.TextArea>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="是否可以打断" name="interruptSwitch" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="回答流程" name="answerFlowType">
                <Select
                  onChange={getAnswerFlowType}
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                >
                  <Option value={0}>等待用户回应</Option>
                  <Option value={1}>回答后挂机</Option>
                  <Option value={2}>跳回原流程节点</Option>
                  <Option value={3}>指定流程节点</Option>
                </Select>
              </Form.Item>
              {answerFlowType === 3 && flowNodes && (
                <Form.Item
                  name="answerFlow"
                  wrapperCol={{ offset: 4 }}
                  style={{ marginTop: '10px' }}
                >
                  <Select getPopupContainer={triggerNode => triggerNode.parentElement}>
                    {flowNodes.map(item => {
                      return (
                        <Option key={item.id} value={item.id}>
                          {item.title}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              )}
            </Col>
          </Row>
          <Row>
            <Col span={12} offset={2}>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={saveLoading}
                  disabled={saveDisable}
                >
                  保存
                </Button>
                <Button
                  type="default"
                  onClick={() => {
                    history.goBack();
                  }}
                >
                  取消
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </div>
      <ExtendQuestion intentionId={questionId} mode="question" fn={updateSave} />
    </>
  );
};

export default OperateQa;
